package main

import (
	"fmt"
	"regexp"
	"strings"
)

// topk(10, disk_free{job="$job",instance="$instance"} + up{job="$job"})
// {"job": "", "instance": "10.20.0.10"}
func replaceLabels(label string, labelMap map[string]string) (string){
	reg := regexp.MustCompile(`{(.*?)}`)
	// [[{job="$job",instance="$instance"} job="$job",instance="$instance"] [{job="$job"} job="$job"]]
	matchList := reg.FindAllStringSubmatch(label, -1)

	for _ , match := range matchList {
		tmpList := strings.Split(match[1], ",")
		ll := []string{}
		reg = regexp.MustCompile(`"\$(.*?)"`)
		var vv string
		var ok bool
		for _, v := range tmpList { // v: mount="$mount"
			tList := reg.FindStringSubmatch(v)
			if len(tList) < 2 {
				continue
			} else {
				key := tList[1]
				vv, ok = labelMap[key]
				if ok {
					if vv == "" || vv == "All" {
						continue
					} else {
						//替换值
						v = strings.ReplaceAll(v, "$"+key, vv)
						ll = append(ll, v)
					}
				} else {
					continue
				}
			}
		}
		label = strings.Replace(label, match[1], strings.Join(ll, ","), 1)
	}
	return label
}

func main(){
	label := "topk(10, disk_free{job=\"$job\",instance=\"$instance\"} + up{job=\"$job\"})"

	labelMap := map[string]string{
		"job": "",
		"instance": "10.20.0.10",
	}
	fmt.Println(replaceLabels(label, labelMap))
}

